package com.cjst.controller.sys;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cjst.controller.base.BaseController;
import com.cjst.pojo.sys.SysMenu;
import com.cjst.pojo.sys.SysRelation;
import com.cjst.pojo.sys.SysRole;
import com.cjst.sdp.util.MapUtils;
import com.cjst.sdp.util.ZTreeNode;
import com.cjst.service.sys.SysDictService;
import com.cjst.service.sys.SysMenuService;
import com.cjst.service.sys.SysRelationService;
import com.cjst.service.sys.SysRoleService;
import com.cjst.sql.C;
import com.cjst.sql.Method;
import com.cjst.sql.WherePrams;
import com.cjst.util.CloneClass;
import com.cjst.util.code.PageUtil;
import com.cjst.util.json.ResultObj;

/**
 * 权限管理
 *
 * @author yj
 */
@Controller
@RequestMapping("/sys/sysRole")
public class SysRoleController extends BaseController {

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysRelationService relationService;

   

    @Autowired
    private SysMenuService menuService;
    
    @Autowired
    private SysDictService dictService;

    /**
     * 跳转到角色列表页面
     */
    @RequestMapping("")
    @RequiresPermissions("role")
    public String index() {
    	
        return "system/role/role";
    }

    /**
     * 查询数据
     */
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    @ResponseBody
    public Object list(Model model, String condition) {
        WherePrams wherePrams = Method.where("delFlag", C.EQ, "0");
        if (StringUtils.isNotEmpty(condition)) {
            wherePrams.and("name", C.LIKE, condition);
        }
        wherePrams.orderBy(" num asc");
        PageUtil<SysRole> pageUtil = sysRoleService.listPageCount(wherePrams);
        List<SysRole> roles = pageUtil.getData();
        List<Map<String, Object>> roleMaps = new ArrayList<>();
        if (roles != null && roles.size() > 0) {
            for (SysRole sysRole : roles) {
                Map<String, Object> roleMap = MapUtils.transBean2Map(sysRole);
                if(StringUtils.isNotEmpty(sysRole.getDataScope())) {
                	String codeVal = dictService.getDictVal("auth_type",sysRole.getDataScope());
                	if(StringUtils.isNotEmpty(codeVal)) {
                		roleMap.put("scopeVal", codeVal);
                	}
                }
                if(StringUtils.isNotEmpty(sysRole.getType())) {
                	String codeVal = dictService.getDictVal("role_type",sysRole.getType());
                	if(StringUtils.isNotEmpty(codeVal)) {
                		roleMap.put("typeVal", codeVal);
                	}
                }
                roleMaps.add(roleMap);

            }
        }
        //转化
        PageUtil<Map<String, Object>> pages = new PageUtil<>();
        CloneClass.getClone(pageUtil, pages);
        pages.setData(roleMaps);
        return super.packForBT(pages);
    }

    /**
     * 跳转到添加页面
     */
    @RequestMapping(value = "/add", method = RequestMethod.GET)
    @RequiresPermissions("role_add")
    public String addSysRole(Model model) {
    	//数据权限
    	List<Map<String, String>> dataScopes = dictService.getDicts("auth_type");
		if(dataScopes!=null&&dataScopes.size()>0) {
			model.addAttribute("dataScopes", dataScopes);
		}
		//角色类型
		List<Map<String, String>> roleTypes = dictService.getDicts("role_type");
		if(roleTypes!=null&&roleTypes.size()>0) {
			model.addAttribute("roleTypes", roleTypes);
		} 
        return "system/role/role_add";
    }

    /**
     * 保存添加
     */
    @RequestMapping(value = "/addRole", method = RequestMethod.POST)
    @ResponseBody
    public Object addSysRole(SysRole sysRole, HttpServletRequest req) {
    	if(sysRole == null) {
			return new ResultObj(1, "参数传递错误，新增角色失败", null);
		}
    	if("1".equals(sysRole.getType())) {
    		return new ResultObj(1, "不允许添加超级管理员角色", null);
    	}
    	//检查名字是否重复
    	WherePrams prams = Method.where("name", C.EQ, sysRole.getName());
    	prams.and("delFlag", C.EQ, "0");
    	List<SysRole> roles = sysRoleService.list(prams);
    	if(roles!=null&&roles.size()>0) {
    		return new ResultObj(1, "角色名重复", null);
    	}
    	//插入并返回角色id
    	String id =  sysRoleService.addLocalByid(sysRole);
        return new ResultObj(0, "新增角色成功", id);
    }

    /**
     * 点击父级编号出现菜单树形结构
     */
    @RequestMapping(value = "/selectRoleTreeList", method = RequestMethod.POST)
    @ResponseBody
    public List<ZTreeNode> selectMenuTreeList() {
        List<ZTreeNode> menuTreeList = sysRoleService.tree();
        menuTreeList.add(ZTreeNode.createParent());
        return menuTreeList;
    }


    /**
     * 跳转到修改页面
     */
    @RequestMapping(value = "/edit/{roleId}", method = RequestMethod.GET)
    @RequiresPermissions("role_edit")
    public String toEditRole(@PathVariable String roleId, Model model) {
        WherePrams where = Method.where("id", C.EQ, roleId);
        SysRole role = sysRoleService.get(where);
        if (role != null) {
            Map<String, Object> roleMap = MapUtils.transBean2Map(role);
            model.addAttribute("role", roleMap);
        }
        //数据权限
    	List<Map<String, String>> dataScopes = dictService.getDicts("auth_type");
		if(dataScopes!=null&&dataScopes.size()>0) {
			model.addAttribute("dataScopes", dataScopes);
		}
		//角色类型
		List<Map<String, String>> roleTypes = dictService.getDicts("role_type");
		if(roleTypes!=null&&roleTypes.size()>0) {
			model.addAttribute("roleTypes", roleTypes);
		}  
        

        return "system/role/role_edit";
    }

    /**
     * 角色详情
     * @param roleId
     * @param model
     * @return
     */
    @RequestMapping(value = "/view/{roleId}", method = RequestMethod.GET)
    @RequiresPermissions("role_view")
    public String toViewRole(@PathVariable String roleId, Model model) {
        WherePrams where = Method.where("id", C.EQ, roleId);
        SysRole role = sysRoleService.get(where);
        if (role != null) {
            Map<String, Object> roleMap = MapUtils.transBean2Map(role);
            model.addAttribute("role", roleMap);
        }
        List<Map<String, String>> codes = dictService.getDicts("auth_type");
		if(codes!=null&&codes.size()>0) {
			model.addAttribute("codes", codes);
		} 

        return "system/role/role_view";
    }

    /**
     * 修改角色
     * @param role
     * @param result
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/editRole", method = RequestMethod.POST)
    @ResponseBody
    @Transactional
    public Object editRole(@Valid SysRole role, BindingResult result) throws Exception {
        if (result.hasErrors()) {
            List<ObjectError> errorList = result.getAllErrors();
            for (ObjectError error : errorList) {
                log.info("ERROR:" + error.getDefaultMessage());
                throw new Exception(error.getDefaultMessage());
            }

        }
        if(role == null) {
           return	new ResultObj(1, "参数传递错误，编辑角色失败", null);
        }
        if(StringUtils.isEmpty(role.getId())) {
        	return	new ResultObj(1, "参数传递错误，编辑角色失败", null);
        }
        //数据库中储存的角色
        SysRole dbRole = sysRoleService.get(role.getId());
        if(dbRole == null) {
        	return	new ResultObj(1, "角色ID不存在，编辑角色失败", null);
        }
        if("1".equals(dbRole.getType())&&!dbRole.getType().equals(role.getType())) {
        	return	new ResultObj(1, "不允许修改超级管理员角色类型", null);
        }
        //检查名字是否重复
    	WherePrams prams = Method.where("name", C.EQ, role.getName());
    	prams.and("delFlag", C.EQ, "0");
    	List<SysRole> roles = sysRoleService.list(prams);
    	if(roles == null) {
    		return new ResultObj(1, "角色名重复", null);
    	}
        
        int flag = sysRoleService.updateLocal(role);
        log.info("=============修改角色成功===============");
        return new ResultObj(0, "修改角色成功", flag);
    }

    /**
     * 删除
     */
    @RequestMapping(value = "/remove")
    @ResponseBody
    @RequiresPermissions("role_remove")
    @Transactional
    public Object remove(@RequestParam String ids) {
        //int flag = menuService.deleteByPrimaryKey(menuId);
        if (StringUtils.isEmpty(ids)) {
            return new ResultObj(1, "参数传递错误", null);
        }
        
        String[] list = ids.split(",");
        //先检查是否包含超级管理员角色，包含则不允许删除
        for (String roleId : list) {
        	SysRole role = sysRoleService.get(roleId);
        	if("1".equals(role.getType())) {
        		return new ResultObj(1, "无法删除超级管理员角色", null);
        	}
            
        }
        for (String roleId : list) {
        	SysRole role = new SysRole();
        	role.setId(roleId);
        	role.setDelFlag("1");
            sysRoleService.updateLocal(role);
        }

        return new ResultObj(0, "删除成功", null);
    }

    /**
     * 角色数据
     * @param roleId
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/toRoleAssign/{roleId}")
    @RequiresPermissions("role_setAuthority")
    public String roleAssign(@PathVariable("roleId") String roleId, Model model) throws Exception {
        if (StringUtils.isEmpty(roleId)) {
            throw new Exception("参数传递为空");
        }
        model.addAttribute("roleId", roleId);
        SysRole role = sysRoleService.get(roleId);
        if (role != null) {
            model.addAttribute("roleName", role.getName());
        }
        return "system/role/role_assign";
    }

    /**
     * 角色权限
     * @param roleId
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/menuTreeListByRoleId/{roleId}")
    @ResponseBody
    public List<ZTreeNode> roleTreeListByUserId(@PathVariable String roleId) throws Exception {
        if (StringUtils.isEmpty(roleId)) {
            throw new Exception("参数传递为空，查询失败");
        }
        WherePrams wherePrams = Method.where("roleid", C.EQ, roleId);
        List<SysRelation> relations = relationService.list(wherePrams);
        //获取拥有的菜单id
        List<String> menuIds = new ArrayList<>();
        for (SysRelation relation : relations) {
            menuIds.add(relation.getMenuid());
        }
        WherePrams menuPrams = Method.where("status", C.EQ, "1");
        //查询整个菜单列表
        List<SysMenu> menus = menuService.list(menuPrams);

        List<ZTreeNode> nodes = new ArrayList<>();
        //遍历menus
        for (SysMenu sysMenu : menus) {
            ZTreeNode node = new ZTreeNode();
            node.setId(sysMenu.getId());
            node.setpId(sysMenu.getParentId());
            node.setName(sysMenu.getName());
            if ("0".equals(sysMenu.getParentId())) {
                node.setIsOpen(true);
            } else {
                node.setIsOpen(false);
            }
            //判断menusId是否为空,查询menus哪些是在menusId中，并给出标记
            if (menuIds.size() > 0 && menuIds.contains(sysMenu.getId())) {
                node.setChecked(true);
            } else {
                node.setChecked(false);
            }
            nodes.add(node);
        }
        return nodes;
    }


    /**
     * 配置权限
     */
    @RequestMapping("/setAuthority")
    @ResponseBody
    @RequiresPermissions("role_setAuthority")
    public Object setAuthority(@RequestParam("roleId") String roleId,
        @RequestParam("ids") String ids) throws Exception {
        if (StringUtils.isEmpty(roleId)) {
            return new ResultObj(1, "参数传递为空，权限配置失败", null);
        }
        relationService.setAuthority(roleId, ids);
        return new ResultObj(0, "成功", null);
    }

}
